package north

import (
	"encoding/json"
	"iot-base/common/config"
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	"iot-base/common/eventtype"
	mqtt "iot-base/common/mqtt"
	"iot-base/dm/common/alarm"
)

func handleSyncAlarms(client mqtt.IOTMQTTBroker, topic string, pCmd *mqtt.Cmd) {
	sql := "select alarm_obj from alarm_states where 1=1 and is_alarm=true"

	rows, err := dbconn.DBConnection.Raw(sql).Rows()
	if err != nil {
		client.Reply(config.GetCloudTopic(), pCmd, DBError, err.Error(), nil)
	} else {
		alarms := make([]*eventtype.Alarm, 0)
		defer rows.Close()
		for rows.Next() {
			var alarmobj eventtype.Alarm
			var alarmbyte []byte
			rows.Scan(&alarmbyte)
			err := json.Unmarshal(alarmbyte, &alarmobj)
			if err == nil {
				alarms = append(alarms, &alarmobj)
			}
		}
		var ids []string
		dbconn.DBConnection.Select("uid").Where("proxy_thing_id=?", config.SelfOption.ID).
			Model(&dbobj.Thing{}).Find(&ids)
		ids = append(ids, config.SelfOption.ID)
		client.Reply(config.GetCloudTopic(), pCmd, 0, "", &alarm.AlarmInfo{
			IDs:    ids,
			Alarms: alarms,
		})
	}

}
